package org.mifos.boss.service;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.mifos.boss.application.model.UserCredentials;
import org.mifos.boss.business.BossDeliveryBusinessInterface;
import org.mifos.boss.domainmodel.CSIndividualSavingsAccount;
import org.mifos.boss.domainmodel.CSLoanAccount;
import org.mifos.boss.domainmodel.CSSavingsAccount;
import org.mifos.boss.domainmodel.ClientCollectionData;
import org.mifos.boss.domainmodel.CollectionSheet;
import org.mifos.boss.service.helper.TimeStamp;
import org.mifos.boss.service.helper.XMLConverter;
import org.mifos.boss.webservice.model.CenterDescription;
import org.mifos.boss.webservice.model.CollectionSheetCustomerDto;
import org.mifos.boss.webservice.model.CollectionSheetCustomerLoanDto;
import org.mifos.boss.webservice.model.CollectionSheetCustomerSavingDto;
import org.mifos.boss.webservice.model.CollectionSheetDto;
import org.mifos.boss.webservice.model.CustomerHierarchy;
import org.mifos.boss.webservice.model.GroupDescription;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.oxm.castor.CastorMarshaller;
import org.springframework.stereotype.Service;
import org.springframework.web.context.support.WebApplicationContextUtils;

@Service(value = "bossDeliveryService")
public class BossDeliveryServiceImpl extends BaseBossService implements
		BossDeliveryServiceInterface {

	protected static Logger logger = Logger
			.getLogger(BossDeliveryServiceImpl.class);

	@Autowired
	private ServletContext servletContext;

	@Autowired
	@Qualifier("bossDeliveryBusiness")
	BossDeliveryBusinessInterface bossDeliveryBusiness;

	// @Autowired
	// XMLConverter converter;

	@Autowired
	CastorMarshaller marshaller;

	public CustomerHierarchy retrieveCustomerHierarchy(UserCredentials user) {
		return bossDeliveryBusiness.retrieveCustomerHierarchy(user);
	}

	public CollectionSheetDto retreiveCollectionSheet(UserCredentials user) {
		CustomerHierarchy custHierarchy = retrieveCustomerHierarchy(user);

		// collection sheet will be retreived on the group level.
		//
		CollectionSheetDto groupCollectionSheet = null;
		List<CenterDescription> centersUnderOfficer = custHierarchy
				.getCenters();
		for (CenterDescription center : centersUnderOfficer) {
			for (GroupDescription group : center.getGroups()) {
				groupCollectionSheet = bossDeliveryBusiness
						.retrieveCollectionSheet(user, group.getId().toString());
				collectionSheet2xmlConverter(
						collectonSheetDto2CollectionSheet((groupCollectionSheet)),
						group.getId().toString());
			}
		}

		// String customerId =
		// Integer.toString(clientsUnderUser.get(0).getId());

		return bossDeliveryBusiness.retrieveCollectionSheet(user, "1");

	}

	public CollectionSheet collectonSheetDto2CollectionSheet(
			CollectionSheetDto collectionSheetDto) {
		return populateCollectionSheet();
		/*
		 * CollectionSheet collectionSheet = new CollectionSheet();
		 * 
		 * List<ClientCollectionData> clientCollectionList = new
		 * ArrayList<ClientCollectionData>();
		 * 
		 * for (CollectionSheetCustomerDto collSheetCustomerDto :
		 * collectionSheetDto.getCollectionSheetCustomer()){
		 * 
		 * ClientCollectionData collData = new ClientCollectionData();
		 * 
		 * //set customer Id
		 * collData.setCustomerId(Integer.toString(collSheetCustomerDto
		 * .getCustomerId()));
		 * 
		 * //set Loan Account List<CSLoanAccount> loanList = new
		 * ArrayList<CSLoanAccount>(); for(CollectionSheetCustomerLoanDto loan :
		 * collSheetCustomerDto.getCollectionSheetCustomerLoan()){ CSLoanAccount
		 * csLoan = new CSLoanAccount();
		 * csLoan.setAccountId(Integer.toString(loan.getAccountId()));
		 * csLoan.setLoanDisbursementAmt(loan.getTotalDisbursement());
		 * csLoan.setLoanRepaymentAmt(loan.getTotalRepaymentDue());
		 * loanList.add(csLoan); }
		 * 
		 * //set saving account List<CSSavingsAccount> savingList = new
		 * ArrayList<CSSavingsAccount>(); for(CollectionSheetCustomerSavingDto
		 * saving : collSheetCustomerDto.getCollectionSheetCustomerSaving()){
		 * CSSavingsAccount csSaving = new CSSavingsAccount();
		 * csSaving.setAccountId(Integer.toString(saving.getAccountId()));
		 * csSaving.setSavingsDue(saving.getDepositDue());
		 * csSaving.setSavingsPaid(saving.getDepositPaid());
		 * savingList.add(csSaving); }
		 * 
		 * 
		 * 
		 * //set Individual saving List<CSIndividualSavingsAccount>
		 * individualSavingList = new ArrayList<CSIndividualSavingsAccount>();
		 * for( CollectionSheetCustomerSavingDto
		 * individual:collSheetCustomerDto.getIndividualSavingAccounts()){
		 * CSIndividualSavingsAccount csIndividual = new
		 * CSIndividualSavingsAccount();
		 * csIndividual.setAccountId(Integer.toString
		 * (individual.getAccountId()));
		 * csIndividual.setDue(individual.getDepositDue());
		 * csIndividual.setPaid(individual.getDepositPaid());
		 * individualSavingList.add(csIndividual); }
		 * 
		 * collData.setLoanAccount(loanList);
		 * collData.setSavingsAccount(savingList);
		 * collData.setIndividualSavings(individualSavingList);
		 * 
		 * clientCollectionList.add(collData);
		 * 
		 * }
		 * 
		 * collectionSheet.setClientCollectionData(clientCollectionList);
		 * 
		 * return collectionSheet;
		 */
	}

	public void collectionSheet2xmlConverter(CollectionSheet collectionSheet,
			String id) {

		XMLConverter converter = new XMLConverter();

		converter.setMarshaller(marshaller);

		// xml file naming convention
		// groupid+ collectionsheet + datetime

		String filename = id + "collectionsheet"
				+ TimeStamp.getCurrentTimestamp();

		File file = new File(filename);

		try {
			converter.convertFromObjectToXML(collectionSheet, file.getPath());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		System.out.println(file.getAbsolutePath() + "  " + file.getName());
	}

	/*
	 * public CollectionSheet xmltocollectionSheetConverter(String xmfilename) {
	 * CollectionSheet collectionSheet = null; ApplicationContext appContext =
	 * new ClassPathXmlApplicationContext( "applicationContext.xml");
	 * XMLConverter converter = (XMLConverter) appContext
	 * .getBean("XMLConverter"); logger.info("Convert XML to CollectionSheet!");
	 * // from XML to object try { collectionSheet = (CollectionSheet) converter
	 * .convertFromXMLToObject(xmfilename); } catch (IOException e) { // TODO
	 * Auto-generated catch block e.printStackTrace(); }
	 * 
	 * return collectionSheet; }
	 */
	public CollectionSheet populateCollectionSheet() {
		CollectionSheet collectionSheet = new CollectionSheet();

		List<ClientCollectionData> clientCollectionList = new ArrayList<ClientCollectionData>();

		for (int iCustomer = 1; iCustomer < 2; iCustomer++) {

			ClientCollectionData collData = new ClientCollectionData();

			// set customer Id
			collData.setCustomerId(Integer.toString(iCustomer));

			// set Loan Account
			List<CSLoanAccount> loanList = new ArrayList<CSLoanAccount>();
			for (int iCustomerLoan = 1; iCustomerLoan < 2; iCustomerLoan++) {
				CSLoanAccount csLoan = new CSLoanAccount();
				csLoan.setAccountId(Integer.toString(iCustomerLoan));
//				csLoan.setLoanDisbursementAmt(iCustomerLoan * 100.00);
				csLoan.setLoanRepaymentAmt(iCustomerLoan * 10.00);
				loanList.add(csLoan);
			}

			// set saving account
			List<CSSavingsAccount> savingList = new ArrayList<CSSavingsAccount>();
			for (int iCustomerSaving = 1; iCustomerSaving < 2; iCustomerSaving++) {
				CSSavingsAccount csSaving = new CSSavingsAccount();
				csSaving.setAccountId(Integer.toString(iCustomerSaving));
				csSaving.setSavingsDue(new BigDecimal(iCustomerSaving * 50.00));
				csSaving.setSavingsPaid(new BigDecimal(iCustomerSaving * 5.00));
				savingList.add(csSaving);
			}

			// set Individual saving
			List<CSIndividualSavingsAccount> individualSavingList = new ArrayList<CSIndividualSavingsAccount>();
			for (int iIndividualSaving = 1; iIndividualSaving < 2; iIndividualSaving++) {
				CSIndividualSavingsAccount csIndividual = new CSIndividualSavingsAccount();
				csIndividual.setAccountId(Integer.toString(iIndividualSaving));
				csIndividual.setDue(new BigDecimal(iIndividualSaving * 10.00));
				csIndividual.setPaid(new BigDecimal(iIndividualSaving * 20.00));
				individualSavingList.add(csIndividual);
			}

			collData.setLoanAccount(loanList);
			collData.setSavingsAccount(savingList);
			collData.setIndividualSavings(individualSavingList);

			clientCollectionList.add(collData);

		}

		collectionSheet.setClientCollectionData(clientCollectionList);
		/*
		 * XMLConverter converter = new XMLConverter();
		 * converter.setMarshaller(marshaller); String xmfilename =
		 * "E:\\somecontent.xml"; try {
		 * converter.convertFromObjectToXML(collectionSheet, xmfilename); }
		 * catch (IOException e) { // TODO Auto-generated catch block
		 * e.printStackTrace(); }
		 */
		return collectionSheet;

	}

	public void convertCollectionSheettoXML(CollectionSheet collectionSheet,
			HttpServletRequest request) {

/*		ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(
				new String[] { "src/main/webapp/WEB-INF/applicationContext.xml" });
		ApplicationContext appContext = new ClassPathXmlApplicationContext("http:WEB-INF/applicationContext.xml"); 
		BeanFactory factory = (BeanFactory) appContext;
		XMLConverter converter = (XMLConverter) factory.getBean("XMLConverter");
*/	
/*		ApplicationContext applicationContext = WebApplicationContextUtils
				.getWebApplicationContext(request.getServletContext());
		if (applicationContext != null
				&& applicationContext.containsBean("XMLConverter")) {
			XMLConverter converter = (XMLConverter) applicationContext
					.getBean("XMLConverter");
*/	
			XMLConverter converter = new XMLConverter();
			converter.setMarshaller(marshaller);

			// String contextPath =
			// request.getServletContext().getRealPath(request.getRequestURI());
			String contextPath = request.getRealPath("/");

			String xmfilename = contextPath + "WEB-INF\\" + "somecontent.xml";
			try {
				converter.convertFromObjectToXML(collectionSheet, xmfilename);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
//		}
	}

}
